//
//  BtnPer.cpp
//  PlantNannyDemo
//
//  Created by Joueu on 14-10-24.
//
//

#include "BtnPer.h"
#include "DictionaryKeyNames.h"
#include "DataCenter.h"

bool BtnPer::init()
{
    if (!ui::Button::init("btn_per_bg@2x.png")) {
        return false;
    }
    this -> tmpForAnimation = 0;
    _tmp = 0;
    this -> setCascadeOpacityEnabled(true);
    m_timer = XKProgressTimer::create("btn_per@2x.png");
    m_timer -> setPosition(this -> getContentSize() * 0.5f);
    this -> addChild(m_timer);
    m_timer -> setPercentage(0);
    m_perLabel = Label::createWithSystemFont("0%", "Arial", 20);
    m_perLabel -> setTextColor(Color4B(0,0,200,0));
    m_perLabel -> setPosition(Point(this -> getContentSize() * 0.5f));
    this -> addChild(m_perLabel, 5);
    return true;
}

void BtnPer::updatePer(int addend)
{
    tmpForAnimation = _to;
    _to = DataCenter::getInstance() -> getCapacityHaveDrink();
    tmpForAnimation = _to - tmpForAnimation;
    
    _toDrink = DataCenter::getInstance() -> getCapacityToDrink();
    m_percentage = _to / _toDrink * 100 < 100 ? _to / _toDrink * 100 : 100;
    m_timer -> runAction(ProgressTo::create(kFreshTime, m_percentage));
    this -> scheduleUpdate();
}

void BtnPer::update(float delta)
{
    updateLbl((delta / kFreshTime) * tmpForAnimation);
}

void BtnPer::updateLbl(float num)
{
    float cur = _tmp;
    cur += num;
    _tmp = cur;
    if ((num > 0 && cur >= _to) || (cur <= _to && num < 0)) {
        this -> unscheduleUpdate();
        m_perLabel -> setString(Value((int)m_percentage).asString() + "%");
        return;
    }
    m_perLabel -> setString(Value(int(cur / _toDrink * 100)).asString() + "%");
}